-- TimeMgr.lua

require("core.Store")

local tinsert = table.insert
local tremove = table.remove

TimeMgr       = singleton()
local prop    = property(TimeMgr)
prop:accessor("timers", {})

function TimeMgr:__init()
end

function TimeMgr:add(interval, repeat_count, callback)
    tinsert(self.timers, {
        interval = interval,
        repeat_count = repeat_count,
        callback = callback,
        execute_time = os.time() + interval
    })
end

function TimeMgr:update(time)
    for index,item in ipairs(self.timers) do
        if time >= item.execute_time then
            item.callback()
            item.execute_time = time + item.interval
            if item.repeat_count == -1 then
                goto continue
            end
            item.repeat_count = item.repeat_count - 1
            if item.repeat_count <= 0 then
                tremove(self.timers, index)
            end
        end
        :: continue ::
    end
end
g_time_mgr = TimeMgr()
